package com.example.fw;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;


import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {

	private Set<GroupObject> groupCache;
	
	public GroupHelper(AppManager manager) {
		super(manager);
		
	}
	
	public Set<GroupObject> getGroups() {
		if (groupCache == null){
			buildGroupCache();
		}
		return groupCache;
	}
	
	private void buildGroupCache() {
		groupCache = new HashSet<GroupObject>();
	
		manager.getNavigationHelper().goToGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name("selected[]"));
//		Set<GroupObject> groups = new HashSet<GroupObject>();
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
			
			Pattern p = Pattern.compile(".*\\((.*)\\)");
			Matcher m = p.matcher(title);
			if (m.matches()) {
				title = m.group(1);	
			}
			GroupObject group = new GroupObject()
				.setName(title)
				.setId(checkbox.getAttribute("value"));
			groupCache.add(group);
		}
	}

	public void createGroup(GroupObject groupObject) {
		
		manager.getNavigationHelper().goToGroupListPage();
		initNewGroupCreation();
		fillInGroupForm(groupObject);
		submitGroupCreation();
		returnToGroupListPage();
		groupCache = null;
	}
	
	public void deleteGroup(GroupObject anyGroup) {
		manager.getNavigationHelper().goToGroupListPage();
		markGroupCheckbox(anyGroup);
		click(By.name("delete"));
		returnToGroupListPage();
		groupCache = null;	
	}
	
	public void modifyGroup(GroupObject anyGroup, GroupObject newGroup) {
		manager.getNavigationHelper().goToGroupListPage();
		initGroupModification(anyGroup);
		fillInGroupForm(newGroup);
		submitGroupModification();
		returnToGroupListPage();
		groupCache = null;
	}

	// creation	
	private void initNewGroupCreation() {
		click(By.name("new"));
	
	}
	private void fillInGroupForm(GroupObject groupObject) {
		type(By.name("group_name"), groupObject.name);
		type(By.name("group_header"), groupObject.header);
		type(By.name("group_footer"), groupObject.footer);
	}
	private void submitGroupCreation() {
		click(By.name("submit"));
	}	

	// modification
		private void initGroupModification(GroupObject anyGroup) {
		markGroupCheckbox(anyGroup);
		click(By.name("edit"));
	}
	private void submitGroupModification() {
		click(By.name("update"));
	}
	
	private void checkGroup(GroupObject group) {
		click(By.name("selected[]"));
	}
	
	private void markGroupCheckbox(GroupObject anyGroup) {
		  WebElement element = driver.findElement(By.xpath("//input[@value='"+anyGroup.id+"']"));
		  element.click();
	}

	// common
	private void returnToGroupListPage() {
		click(By.linkText("group page"));
	}
}







